package com.levy.contronller.javase.proxy.cglibProxy;


import com.levy.contronller.javase.proxy.Hello;
import com.levy.contronller.javase.proxy.HelloImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by levy on 2019/6/16.
 */
public class CglibProxy implements MethodInterceptor {

    private static CglibProxy instance = new CglibProxy();

    private CglibProxy(){

    }

    public static CglibProxy getInstance(){
        return instance;
    }
    /**
     * 代理对象
     */
    private Object targetObj;

    public <T> T getProxy(Class<T> cls) {
        return  (T)Enhancer.create(cls,this);
    }

    @Override
    public Object intercept(Object obj, Method arg1, Object[] arg2,
                            MethodProxy proxy) throws Throwable {

        brefore();

        Object object = proxy.invokeSuper(obj, arg2);

        after();
        return object;
    }


    private void brefore() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }


    public static void main(String[] args) {
        Hello proxy = CglibProxy.getInstance().getProxy(HelloImpl.class);
        proxy.say("ser");
    }

}
